
package current.security.init.listener;

import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.apache.log4j.Logger;
import org.springframework.web.context.support.WebApplicationContextUtils;

import current.security.init.SecurityService;

/**
 * @author Downpour
 */
public class ServletContextLoaderListener implements ServletContextListener {
	private Logger log = Logger.getLogger(ServletContextLoaderListener.class);
    /* (non-Javadoc)
     * @see javax.servlet.ServletContextListener#contextInitialized(javax.servlet.ServletContextEvent)
     */
    public void contextInitialized(ServletContextEvent servletContextEvent) {
        ServletContext servletContext = servletContextEvent.getServletContext();
        SecurityService securityService = this.getSecurityService(servletContext);
        Map<String, String> urlAuthorities = null;
		try {
			urlAuthorities = securityService.queryAllMap();
		} catch (Exception e) {
			e.printStackTrace();
		}
        servletContext.setAttribute("urlAuthorities", urlAuthorities);
        log.debug("数据库中的URL资源为："+urlAuthorities);
    }

    
    /* (non-Javadoc)
     * @see javax.servlet.ServletContextListener#contextDestroyed(javax.servlet.ServletContextEvent)
     */
    public void contextDestroyed(ServletContextEvent servletContextEvent) {
    	servletContextEvent.getServletContext().removeAttribute("urlAuthorities");
    }

    /**
     * Get SecurityManager from ApplicationContext
     * 
     * @param servletContext
     * @return
     */
    protected SecurityService getSecurityService(ServletContext servletContext) {
       return (SecurityService) WebApplicationContextUtils.getWebApplicationContext(servletContext).getBean("securityService"); 
    }

}
